<template>
  <el-dialog title="配置数据源" :close-on-click-modal="false" visible :close-on-press-escape="false" :before-close="close"
    destroy-on-close>
    <el-button size="small" type="primary" style="margin:15px 0;" @click="addTab()">
      添加级
    </el-button>
    <el-tabs v-model="editableTabsValue" type="card" @tab-remove="removeTab" :before-leave="changeTab">
      <el-tab-pane :key="item.name" v-for="(item, index) in editableTabs" :label="`${toChineseNumber(index+1)}级数据源`"
        :name="item.name" :closable="index===editableTabs.length-1">
        <el-form :model="formData[index]" label-width="90px" ref="levelForm" label-position="right">
          <el-row>
            <el-form-item label="表单" prop="tableName"  :rules="[{
                required: true,
                message: '请选择表单',
                trigger:'blur'
                }]">
                <el-select filterable v-model="formData[index].tableName" @change="(curVal) => changeTable(curVal, index)" style="width:40%;">
                    <el-option v-for="opt in tableOptions" :key="opt.value" :label="opt.label" :value="opt.value"></el-option>
                </el-select>
            </el-form-item>
            <el-col v-for="(data, ind) in formData[index].datas" :key="ind">
                <el-form-item label="显示字段" :prop="`datas.${ind}.showName`"
                :rules="[{
                    required: true,
                    message: '请选择显示字段',
                    trigger:'change'
                }]">
                <el-select filterable v-model="data.showName" style="width:40%;" @change="validateChange(index)">
                  <el-option v-for="opt in fieldOptions" :key="opt.value" :label="opt.label" :value="opt.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="数据字段" :prop="`datas.${ind}.fieldName`"
                :rules="[{
                    required: true,
                    message: '请选择数据字段',
                    trigger:'change'
                }]">
                <el-select filterable v-model="data.fieldName" style="width:40%;" @change="validateChange(index)">
                  <el-option v-for="opt in fieldOptions" :key="opt.value" :label="opt.label" :value="opt.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="index > 0" label="父级字段" :prop="`datas.${ind}.parent`"
                :rules="[{
                    required: true,
                    message: '请选择父级字段',
                    trigger:'change'
                }]">
                <el-select filterable v-model="data.parent" style="width:40%;" @change="validateChange(index)">
                  <el-option v-for="opt in fieldOptions" :key="opt.value" :label="opt.label" :value="opt.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer">
      <el-button type="primary" @click="handelConfirm" size="small">
        确定
      </el-button>
      <el-button @click="close" size="small">
        取消
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {
    getTableNameListForm,
    getAllForm,
    getTableColumn,
    listchoose,
    sourceTestList
  } from '@/api/custom/formDesigner'
  import {
    toChineseNum
  } from '@/utils/toChineseNum'
  export default {
    props: ['fields', 'formName'],
    data() {
      return {
        editableTabsValue: '1', //当前tab页
        basic: {
          tableName: '' //表单名
        },
        formData: [], //各级配置
        tableOptions: [], //表选项
        fieldOptions: [], //表字段选项
        editableTabs: [], //tab页
        tabIndex: 1 //当前最大tab
      }
    },
    mounted() {
      this.getTableName() //获取所有表名
      this.tabIndex = this.fields.length + 1
      this.formData = [...this.fields]
      this.formData.length > 0 && this.formData.map((item, index) => {
        if (index === 0) {
          this.editableTabsValue = item.name
        }
        this.editableTabs.push({
          name: item.name,
          tableName: item.tableName
        })
      })
      if (this.editableTabs.length > 0) {
        this.getFieldOption(this.editableTabs[0].tableName) //获取表字段
      }
    },
    methods: {
      //确认
      handelConfirm() {
        if (Array.isArray(this.$refs.levelForm)) {
            this.$refs.levelForm[this.$refs.levelForm.length - 1].validate((valid) => {
                if (valid) {
                this.$emit('commit', this.formData)
                this.close()
                return true
                } else {
                this.$message.error('请补全各级数据源')
                return false
                }
            })
        } else {
            this.$refs.levelForm.validate((valid) => {
                if (valid) {
                this.$emit('commit', this.formData)
                this.close()
                return true
                } else {
                this.$message.error('请补全各级数据源')
                return false
                }
            })
        }
      },
      //取消
      close() {
        this.editableTabs = []
        this.editableTabsValue = '1'
        this.formData = []
        this.$emit('close')
      },
      //获取父级字段
      getParent(index) {
        return this.formData[index - 1].datas.map((item, ind) => {
          let label = this.fieldOptions.filter((opt) => {
            return opt.value === item.fieldName
          })
          return {
            label: label.length > 0 ? label[0].label : item.fieldName,
            value: item.fieldName
          }
        })
      },
      //更改表单
      changeTable(val, index) {
        this.fieldOptions = []
        this.getFieldOption(val)
        this.formData[index].datas.forEach((data)=>{
            data.fieldName = ''
            data.showName = ''
            data.parent = ''
        })
        this.validateChange(index)
        // this.formData.map((item)=>{
        //   const xx = item.datas.map((data)=>{
        //     data.fieldName = ''
        //     data.parent = ''
        //   })
        //   return xx
        // })
        // this.editableTabsValue = '1'
      },
      validateChange (index) {
        this.$refs.levelForm[index].validate()
      },
      //切换tab页，上层各级都配置完成后才能点击切换后面的级
      changeTab(name, oldName) {
        if (name !== '1') {
          let change = false
          this.$refs.levelForm[Number(oldName) - 1].validate((valid) => {
            change = valid
            if (valid) {
              return true
            } else {
              return false
            }
          })
          return change
        } else {
          return true
        }
      },
      //获取所有表名
      getTableName() {
        listchoose().then((res) => {
            if (res.code === 0) {
            this.tableOptions = res.data.map((item)=>{
                return {
                label:item.name,
                value:item.id
                }
            })
            }
        }).catch(e=>console.log(e))
      },
      //获取表字段
      getFieldOption(id) {
        sourceTestList(id).then((res) => {
            if (res.code === 0) {
                this.fieldOptions = res.data?.columns.map((item) => {
                    return {label:item.name,value:item.name}
                })
            }
        })
      },
      //添加tab页，添加级
      addTab() {
        if (this.editableTabs.length === 4) {
            this.$message.warning('最多添加四级数据源')
            return
        }
        let newTabName = this.tabIndex + '';
        this.editableTabs.push({
          name: newTabName,
          tableName: '',
        });
        this.formData.push({
          datas: [{
            showName: '',
            fieldName: '', //显示字段
            parent: '' //父级字段
          }], //该级的数据源配置数组
          name: newTabName,
        })
        this.editableTabsValue = newTabName;
        this.tabIndex++
      },
      //删除tab页，删除级
      removeTab(targetName) {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
              this.formData = this.formData.filter(data => data.name !== targetName)
            }
          });
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
        this.tabIndex--
      },
      //数字转成中文
      toChineseNumber(num) {
        return toChineseNum(num)
      }
    }
  }

</script>
